package house.service;

import house.entity.Res;
import house.entity.User;
import house.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public Res login(String username, String password) {
        User user = userRepository.findOneByUsername(username);
        if (user == null) {
            return new Res(400, "用户不存在", null);
        } else if (user.getPassword().equals(password)) {
            return new Res(200, "登录成功", user);
        } else {
            return new Res(400, "用户名或密码错误", null);
        }
    }

    public Res register(String username, String password, String role, String realName, String phone, String idcode) {
        User user = userRepository.findOneByUsername(username);
        if (user != null) {
            return new Res(400, "用户名已存在", null);
        } else {
            User newUser = new User(username, password, role, realName, phone, idcode);
            userRepository.save(newUser);
            return new Res(200, "注册成功", newUser);
        }

    }

    public Res register(User user) {
        if (user == null) {
            return new Res(400, "", null);
        }
        User user1 = userRepository.findOneByUsername(user.getUsername());
        if (user1 != null) {
            return new Res(400, "用户名已存在", null);
        } else {
            userRepository.save(user);
            return new Res(200, "注册成功", user);
        }

    }
}
